<template>
<el-form ref="postForm" label-width="150px" class="ruleForm" :model="form" :rules="rules">
  <div class="page-container">
    <div class="form-title">基础信息</div>
    <el-form-item label="角色名称：" prop="name">
      <el-col :span="10">
        <el-input v-model="form.name" placeholder="请输入角色名称" />
      </el-col>
    </el-form-item>
    <el-form-item label="角色描述：" prop="remark">
      <el-col :span="10">
        <el-input v-model="form.remark" placeholder="请输入角色描述" />
      </el-col>
    </el-form-item>
    <div class="form-title">角色权限</div>
    <div class="role-right" v-for="group in list" :key="group.name">
        <div class="right-title">
          <el-checkbox :indeterminate="group.indeterminate" @change="handleParentChange(group)" v-model="group.checked">{{ group.name }}</el-checkbox>
        </div>
        <template v-if="group.children">
          <div class="ml40" v-for="onerole in group.children" :key="onerole.name">
              <el-checkbox :indeterminate="onerole.indeterminate" @change="handleItemChange([onerole, group])" v-model="onerole.checked">{{ onerole.name }}</el-checkbox>
              <template v-if="onerole.children">
                <div class="ml40" v-for="towrole in onerole.children" :key="towrole.name">
                  <el-checkbox :indeterminate="towrole.indeterminate" @change="handleItemChange([towrole, onerole, group])" v-model="towrole.checked">{{ towrole.name }}</el-checkbox>
                  <ul>
                    <li v-for="threeole in towrole.permissions" :key="threeole.id">
                      <el-checkbox @change="handleItemChange([threeole, towrole, onerole, group])" v-model="threeole.checked">{{ threeole.name }}</el-checkbox>
                    </li>
                  </ul>
                </div>
              </template>
              <template v-else>
                <ul>
                  <li v-for="towrole in onerole.permissions" :key="towrole.id">
                    <el-checkbox @change="handleItemChange([towrole, onerole, group])" v-model="towrole.checked">{{ towrole.name }}</el-checkbox>
                  </li>
                </ul>
              </template>
          </div>
        </template>
        <template v-else>
          <!--一级-->
          <ul>
            <li v-for="onerole in group.permissions" :key="onerole.id">
              <el-checkbox @change="handleItemChange([onerole, group])" v-model="onerole.checked">{{ onerole.name }}</el-checkbox>
            </li>
          </ul>
        </template>
      </div>
  </div>
</el-form>
<div class="footer">
  <el-button @click="router.push('/setting/role')">取消</el-button>
  <el-button type="primary" @click="handleSave(postForm)">确定</el-button>
</div>
</template>
<script lang="ts" setup>
import {ref, reactive,onMounted} from 'vue'
import {useRouter,useRoute} from 'vue-router'
import {RoleDetails, RoleSave} from '@/api/role'
import {ElForm, ElMessage} from 'element-plus'
const router = useRouter()
const form = ref<RoleEditor>({
  id: useRoute().query.id ? Number(useRoute().query.id) : 0,
  name: '',
  remark: '',
  privileges: []
})
const rules = reactive({
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
})
const list = ref<Menu[]>([]) //全部导航列表
let privilege:RolePrivilege[] = ([]) //选中的权限
type FormInstance = InstanceType<typeof ElForm>
const postForm = ref<FormInstance>()

const loadData = (): void => {
  RoleDetails({ id: form.value.id }).then((res: ServiceResponse<RoleDetails>) => {
    if (res.success) {
      list.value = res.data?.privileges ?? []
      if (res.data?.role) {
        form.value = res.data.role
        list.value.forEach((item: Menu) => {
          setGroupCheck(item)
          setGroupIndeterminate(item)
        })
      }
    }
  })
}
const setGroupCheck = (group: Menu): void => {
  if (group.permissions) {
    group.permissions.forEach((permission: Privilege) => {
      permission.checked = form.value.privileges.filter((p:RolePrivilege) => p.privilege === permission.id && p.route === group.route).length > 0
    })
  } else {
    group.children?.forEach((item: Menu) => {
      setGroupCheck(item)
    })
  }
}
const setGroupIndeterminate = (group: Menu): void => {
    if (group.children) {
      group.children.forEach((item: Menu) => {
        setGroupIndeterminate(item)
      })
    }
    updateCheck(group)
}

 //修改是否选中和半选
const updateCheck = (group: Menu): void => {
    group.indeterminate = false
    group.checked = false
    let checklength = 0
    let length = 0
    if (group.permissions) {
      checklength = group.permissions.filter((p) => p.checked).length
      length = group.permissions.length
    } else {
      checklength = group.children?.filter((p) => p.checked).length ?? 0
      length = group.children?.length ?? 0
    }
    if (checklength > 0) {
      if (checklength === length) group.checked = true
      else group.indeterminate = true
    } else {
      if (group.children && group.children.filter((p) => p.indeterminate).length > 0) {
        group.indeterminate = true
      }
    }
}
const getRolePrivilege = (group: Menu): void => {
  if (group.permissions) {
    group.permissions.forEach((item: Privilege) => {
      if (item.checked) {
        const rolePrivilege = reactive<RolePrivilege>({
          id: 0,
          roleId: form.value.id,
          route: group.route,
          privilege: item.id
        })
        privilege.push(rolePrivilege)
      }
    })
  } else {
    group.children?.forEach((item: Menu) => {
      getRolePrivilege(item)
    })
  }
}
const handleItemChange = (groups: any): void => {
  groups.forEach((group: Menu, index: number) => {
    if (index === 0) handleParentChange(group)
    else updateCheck(group)
  })
}

//点击父级菜单
const handleParentChange = (group: Menu): void => {
    group.indeterminate = false
    if (group.permissions) {
      group.permissions.forEach((permission: Privilege) => {
        permission.checked = group.checked
      })
    } else if (group.children) {
      group.children.forEach((item: Menu) => {
        item.checked = group.checked
        handleParentChange(item)
      })
    }
}
const handleSave  = (formEl: FormInstance | undefined): void => {
  if (!formEl) return
  formEl.validate((valid) => {
    if(valid) {
      privilege = []
      list.value.forEach((group: Menu) => {
        getRolePrivilege(group)
      })
      if (privilege.length === 0) return ElMessage.error('请选择角色权限')
      form.value.privileges = privilege
      RoleSave(form.value).then((res: ServiceResponse<any>) => {
        if (res.success) {
          ElMessage.success('操作成功')
          router.push('/setting/role')
        } else ElMessage.error(res.msg)
      })
    }
  })
}
onMounted(() => {
  loadData()
})
</script>
<style lang="scss" scoped>
  @import '@/assets/styles/mixin.scss';
  @import '@/assets/styles/formPage.scss';

  $bg-color: #f7f8f9;
.page-container {
  margin-bottom: 50px;
}
  .add-role {
    padding-bottom: 24px;
  }
  .right-title {
    display: flex;
    height: 52px;
    align-items: center;
    padding-left: 16px;
    padding-right: 16px;
    background-color: rgba(0, 0, 0, 0.03);
    color: rgba(0, 0, 0, 0.85);
  }
  .role-right {
    ul {
      display: flex;
      margin: 8px 0 16px;
      padding: 0 40px;
      flex-wrap: wrap;
    }

    li {
      padding: 7px 24px 7px 0;
    }
  }
  .save {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    padding-left: 185px;
    display: flex;
    justify-content: center;
    background-color: #fff;
    z-index: 1;
  }
  ::v-deep {
    .el-checkbox {
      color: rgba(0, 0, 0, 0.65);
    }

    .is-checked .el-checkbox__label {
      color: rgba(0, 0, 0, 0.65);
    }
  }
  .ml40 {
    margin-left: 40px;
  }
</style>
